package logic

import (
	"context"

	"jinrigaoping/rpc/sys/internal/model"
	"jinrigaoping/rpc/sys/internal/svc"
	"jinrigaoping/rpc/sys/sys"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type SysRoleUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSysRoleUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SysRoleUpdateLogic {
	return &SysRoleUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SysRoleUpdateLogic) SysRoleUpdate(in *sys.SysRoleUpdateReq) (*sys.SysRoleUpdateRes, error) {

	err := l.svcCtx.SysRoleModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {

		if err := l.svcCtx.SysRoleModel.TransUpdate(l.ctx, session, &model.SysRole{
			Id:       in.Id,
			RoleName: in.RoleName,
			Remark:   in.Remark,
		}); err != nil {
			return err
		}

		if err := l.svcCtx.SysRoleMenuModel.TransDelete(l.ctx, session, in.Id); err != nil {
			return err
		}

		if len(in.MenuIdList) > 0 {
			var sysRoleMenuList = make([]model.SysRoleMenu, len(in.MenuIdList))
			for i, v := range in.MenuIdList {
				sysRoleMenuList[i] = model.SysRoleMenu{
					Id:     0,
					RoleId: in.Id,
					MenuId: v,
				}
			}

			if err := l.svcCtx.SysRoleMenuModel.TransInsertBatch(l.ctx, session, sysRoleMenuList); err != nil {
				return err
			}
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	return &sys.SysRoleUpdateRes{}, nil
}
